<template>
  <div class="add-incoming-inspection-container">
    <div class="form-header">
      <h2>添加来科检查</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
        class="inspection-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检验编号" prop="incomingNumber" required>
                  <div class="search-input-container">
                    <el-input 
                      v-model="formData.incomingNumber" 
                      :disabled="isAutoGenerate"
                      placeholder="IQC+年月日时分秒"
                    ></el-input>
                    <el-switch 
                      v-model="isAutoGenerate" 
                      class="generate-switch" 
                      active-text="自动生成"
                    ></el-switch>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检验类型" prop="incomingName" required>
                  <el-select v-model="formData.incomingName" placeholder="请选择检验类型" style="width: 100%" disabled>
                    <el-option label="来料检验" value="来料检验"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="产品编码" prop="productCode">
                  <el-input v-model="formData.productCode" placeholder="请输入产品编码" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="产品名称" prop="productName">
                  <el-input v-model="formData.productName" placeholder="请输入产品名称" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商编码" prop="supplierCode">
                  <el-input v-model="formData.supplierCode" placeholder="请输入供应商编码"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="供应商名称" prop="supplierName">
                  <el-input v-model="formData.supplierName" placeholder="请输入供应商名称"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="供应商批次号" prop="supplierBatch">
                  <el-input v-model="formData.supplierBatch" placeholder="请输入供应商批次号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="formData.unit" placeholder="请输入单位"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <div class="inspection-header">检测情况</div>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="本次检验数量" prop="receivedCount" required>
                  <div class="number-input-container">
                    <el-button @click="decreaseQuantity" :disabled="formData.receivedCount <= 1">
                      <el-icon><Minus /></el-icon>
                    </el-button>
                    <el-input-number v-model="formData.receivedCount" :min="0" controls-position="right" style="width: 100%"></el-input-number>
                    <el-button @click="increaseQuantity">
                      <el-icon><Plus /></el-icon>
                    </el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合格品数量" prop="inspectedCount" required>
                  <el-input-number v-model="formData.inspectedCount" :min="0" :max="formData.receivedCount" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="不合格数量" prop="nonConformityCount" required>
                  <el-input-number v-model="formData.nonConformityCount" :min="0" :max="formData.receivedCount" style="width: 100%"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="来料日期" prop="incomingTime">
                  <el-date-picker
                    v-model="formData.incomingTime"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检验日期" prop="inspectionTime" required>
                  <el-date-picker
                    v-model="formData.inspectionTime"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="检验结果" prop="inspectionConclusion" required>
                  <el-select v-model="formData.inspectionConclusion" placeholder="请选择检验结果" style="width: 100%">
                    <el-option label="请选择检测结果" value=""></el-option>
                    <el-option label="通过" value="通过"></el-option>
                    <el-option label="不通过" value="不通过"></el-option>
                    <el-option label="部分通过" value="部分通过"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="检验员" prop="inspectors">
                  <el-input v-model="formData.inspectors" placeholder="请输入检验员姓名"></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <div class="inspection-header">检验参数</div>
            
            <el-collapse v-model="activeNames">
              <el-collapse-item title="检验参数" name="1">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="加工检测标准" prop="processStandard">
                      <el-input v-model="formData.processStandard" placeholder="请输入加工检测标准"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="产品检测标准" prop="productStandard">
                      <el-input v-model="formData.productStandard" placeholder="请输入产品检测标准"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="轻微缺陷标准" prop="minorDefectStandard">
                      <el-input v-model="formData.minorDefectStandard" placeholder="请输入轻微缺陷标准"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="加工检测数值" prop="processValue">
                      <el-input v-model="formData.processValue" placeholder="请输入加工检测数值"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="产品检测数值" prop="productValue">
                      <el-input v-model="formData.productValue" placeholder="请输入产品检测数值"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="轻微缺陷数值" prop="minorDefectValue">
                      <el-input v-model="formData.minorDefectValue" placeholder="请输入轻微缺陷数值"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import http from '@/api/http';
import { Plus, Minus } from '@element-plus/icons-vue';

const router = useRouter();
const route = useRoute();

// 获取待检任务ID
const waitTaskId = ref(route.query.id);

// 表单引用
const formRef = ref(null);

// 生成检验编号
const generateInspectionCode = () => {
  try {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    
    return `IQC${year}${month}${day}${hours}${minutes}${seconds}`;
  } catch (error) {
    console.error('生成检验编号失败:', error);
    // 备选方案
    return `IQC${Date.now()}`;
  }
};

// 是否自动生成编号
const isAutoGenerate = ref(true);

// 折叠面板激活的名称
const activeNames = ref(['1']);

// 表单数据
const formData = reactive({
  id: 0,
  incomingNumber: '',          // 来料检验编号
  incomingName: '',            // 来料检验名称
  supplierBatch: '',           // 供应商批次号
  supplierName: '',            // 供应商名称
  productCode: '',             // 产品物料编码
  productName: '',             // 产品物料名称
  receivedCount: 0,            // 接收数量
  inspectedCount: 0,           // 检测数量
  nonConformityCount: 0,       // 不合格数量
  inspectionConclusion: '',    // 检测结论
  incomingTime: '',            // 来料日期
  inspectionTime: '',          // 检测日期
  states: 0,                   // 状态
  inspectors: '',              // 检测人员
  supplierCode: '',            // 供应商编码
  unit: '',                    // 单位
  remark: '',                   // 备注
  processStandard: '',
  productStandard: '',
  minorDefectStandard: '',
  processValue: '',
  productValue: '',
  minorDefectValue: ''
});

// 表单验证规则
const formRules = reactive({
  incomingNumber: [
    { required: !isAutoGenerate.value, message: '请输入检验编号', trigger: 'blur' }
  ],
  incomingName: [
    { required: true, message: '请选择检验类型', trigger: 'change' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  receivedCount: [
    { required: true, message: '请输入检验数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  inspectedCount: [
    { required: true, message: '请输入合格品数量', trigger: 'blur' }
  ],
  nonConformityCount: [
    { required: true, message: '请输入不合格品数量', trigger: 'blur' }
  ],
  inspectionTime: [
    { required: true, message: '请选择检验日期', trigger: 'change' }
  ],
  inspectionConclusion: [
    { required: true, message: '请选择检验结果', trigger: 'change' }
  ],
  inspectors: [
    { required: true, message: '请输入检验员姓名', trigger: 'blur' }
  ]
});

// 监听自动生成状态变化
watch(isAutoGenerate, (val) => {
  formRules.incomingNumber[0].required = !val;
  if (val) {
    // 如果开启自动生成，则生成新编号
    formData.incomingNumber = generateInspectionCode();
  }
});

// 增加/减少数量
const increaseQuantity = () => {
  formData.receivedCount += 1;
};

const decreaseQuantity = () => {
  if (formData.receivedCount > 1) {
    formData.receivedCount -= 1;
  }
};

// 返回列表页
const goBack = () => {
  router.push('/WaitTask');
};

// 获取待检任务和产品详情数据
const fetchDetail = async (id) => {
  try {
    console.log(id);
    
    const response = await http.get(`/api/WaitTask/GetWaitTaskById/${id}`);
    console.log(' 获取待检任务和产品详情数据:', response);
    
    if (response && response.data) {
      // 特别处理产品信息
      if (response.data.materialCode) {
        formData.productCode = response.data.materialCode;
      }
      
      if (response.data.materialName) {
        formData.productName = response.data.materialName;
      }
      
      // 设置其他默认值
      if (!formData.inspectedCount) formData.inspectedCount = 0;
      if (!formData.nonConformityCount) formData.nonConformityCount = 0;
      if (!formData.inspectionTime) formData.inspectionTime = new Date().toISOString().split('T')[0];
      if (!formData.incomingTime) formData.incomingTime = new Date().toISOString().split('T')[0];
      if (!formData.incomingName) formData.incomingName = '来料检验';
    } else {
      ElMessage.error('获取待检任务和产品详情数据失败');
    }
  } catch (error) {
    console.error(' 获取待检任务和产品详情数据出错:', error);
    ElMessage.error(' 获取待检任务和产品详情数据失败，请稍后再试');
  }
};

// 初始化
onMounted(() => {
  // 如果有待检任务ID，获取详情数据
  if (route.query.id) {
    fetchDetail(route.query.id);
  }
});

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    // 准备提交的数据
    const submitData = { ...formData };
    
    // 如果开启自动生成，刷新编号
    if (isAutoGenerate.value) {
      submitData.incomingNumber = generateInspectionCode();
    }
    
    // 添加待检任务ID
    if (waitTaskId.value) {
      submitData.waitTaskId = waitTaskId.value;
    }
    
    // 调用添加API
    const url = `/api/WaitTask/AddIncominginspection`;
    

    const response = await http.post(url, submitData);
    
    if (response ) {
      ElMessage.success('添加来科检查成功');
      goBack();
    } else {
      ElMessage.error(response?.msg || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('操作失败，请稍后再试');
  }
};
</script>

<style scoped>
.add-incoming-inspection-container {
  padding: 20px;
}

.form-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.form-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.form-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-section {
  margin-bottom: 30px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.section-content {
  padding: 20px;
}

.inspection-header {
  margin: 20px 0 10px;
  font-weight: bold;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.refresh-btn {
  margin-left: 5px;
  padding: 4px;
}

.search-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.search-input-container .el-input {
  flex: 1;
}

.generate-switch {
  margin-left: 10px;
}

.number-input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.number-input-container .el-input-number {
  margin: 0 5px;
  flex: 1;
}

.number-input-container .el-button {
  padding: 8px;
  border-radius: 4px;
}

.number-input-container :deep(.el-input-number__decrease),
.number-input-container :deep(.el-input-number__increase) {
  display: none;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.inspection-form :deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

:deep(.el-form-item__error) {
  padding-top: 2px;
}
</style>
